package oh.june.imagestogif;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MakeGifActivity extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_convert);
		
		Button btnConvert = (Button)findViewById(R.id.btn_convert);
		btnConvert.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				converToGif();
			}
		});
		
	}

	protected void converToGif() {
		Intent i = getIntent();
		Bundle bundle = i.getExtras();
		ArrayList<String> seri = (ArrayList<String>)bundle.getSerializable("PICTURE_PATH_LIST");
		if(seri.size() == 0)
			return;
			
		AnimatedGifEncoder encoder = new AnimatedGifEncoder();
		
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = sdf.format(new Date());
			
			File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/gifviewer");
			if(!dir.exists())
				dir.mkdir();
			File outputFile = new File(dir, fileName + ".gif");
			if(outputFile.exists())
				outputFile.delete();
			outputFile.createNewFile();
		
			FileOutputStream fous = new FileOutputStream(outputFile);
			encoder.setDelay(750);
			encoder.start(fous);
			
			for(String picturePath : seri){
				encoder.addFrame(BitmapFactory.decodeFile(picturePath));	
			}
			
			encoder.finish();
			fous.close();
			
			GIFView viewer = (GIFView)findViewById(R.id.gifviewer);
			viewer.setImagePath(outputFile.getAbsolutePath());
			viewer.invalidate();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		
	}
	
}
